package com.sixbro.authorization.service;

import com.sixbro.common.domain.Principal;
import com.sixbro.common.domain.Privilege;
import com.sixbro.common.domain.Role;
import com.sixbro.common.domain.Scope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/12/6 14:26
 */
@Slf4j
public class OAuth2UserDetailsService implements UserDetailsService {

    private PasswordEncoder encoder;

    public OAuth2UserDetailsService(PasswordEncoder encoder) {
        this.encoder = encoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<Privilege> privileges = new ArrayList<>();
        privileges.add(Privilege.builder().id(System.currentTimeMillis()).name("文件添加").privilege("file:add").description("文件添加").build());
        privileges.add(Privilege.builder().id(System.currentTimeMillis()).name("文件編輯").privilege("file:edit").description("文件編輯").build());
        privileges.add(Privilege.builder().id(System.currentTimeMillis()).name("文件刪除").privilege("file:delete").description("文件刪除").build());

        Set<Role> roles = new HashSet<>();
        roles.add(Role.builder().id(System.currentTimeMillis()).role("admin").name("管理员").description("管理员").privileges(privileges).build());

        String id = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
        return Principal.create(id, username, encoder.encode("123456"), roles, Scope.Alipay);
    }
}
